package com.example.hxds.workflow.config;
import cn.hutool.json.JSONObject;
import com.example.hxds.common.exception.HxdsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
 * @Author XUYANG
 * @Date 2024-04-10 14:41
 */
@RestControllerAdvice
public class ExceptionAdvice {
    private static final Logger log = LoggerFactory.getLogger(com.example.hxds.workflow.config.ExceptionAdvice.class);

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({Exception.class})
    public String exceptionHandler(Exception e) {
        JSONObject jsonObject = new JSONObject();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException)e;
            jsonObject.set("error", methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {
            jsonObject.set("error", "Web方法不支持当前请求");
        } else if (e instanceof org.springframework.http.converter.HttpMessageNotReadableException) {
            jsonObject.set("error", "缺少提交数据");
        } else if (e instanceof HxdsException) {
            log.error("执行异常", e);
            HxdsException hxdsException = (HxdsException)e;
            jsonObject.set("error", hxdsException.getMsg());
        } else {
            log.error("执行异常", e);
            jsonObject.set("error", "执行异常");
        }
        return jsonObject.toString();
    }
}

